package com.xunshibao.web.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xunshibao.web.SessionUser;

public class SecurityInterceptor extends HandlerInterceptorAdapter {
    private String loginUrl = "/user/login.jhtml";

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Security sec = handler.getClass().getAnnotation(Security.class);
        if (sec != null) {
        	HttpSession session = request.getSession();
            if (session != null && session.getAttribute(SessionUser.KEY) == null) {
                String url = request.getPathInfo();
                response.sendRedirect(request.getContextPath() + loginUrl + "?url=" + url);
                return false;
            }
        }
        return true;
    }
}
